package com.droowa.model.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.droowa.domain.BoardManagement;
import com.droowa.domain.BoardPaper;
import com.droowa.util.BoardUtilities;

@Repository
public class BoardPaperDAOImpl implements BoardPaperDAO {

	@Autowired
	private SqlSessionTemplate session;
	
	@Override
	public List<BoardPaper> selectBoardPaperList(BoardManagement bm, int page) throws SQLException {
		HashMap map = makeTableMap(bm.getBoardId());
		map.put("contentPerPage", bm.getPagingListNum());
		map.put("page", page);
		return session.selectList(makeSqlId("selectBoardPaperList"), map);
	}

	@Override
	public int selectTotalContent(int bid) throws SQLException {
		HashMap map = makeTableMap(bid);
		return session.selectOne(makeSqlId("selectTotalContent"), map);
	}
	
	@Override
	public int insertContentForNewCount(BoardPaper paper, int bid) {
		paper.setBoardId(makeTableName(bid));
		return session.insert(makeSqlId("insertContentForNewCount"), paper);
	}

	@Override
	public int updateViewCount(int bid, int num)
			throws SQLException {
		HashMap map = makeTableMap(bid);
		map.put("num", num);
		return session.update(makeSqlId("updateViewCount"), map);
	}

	@Override
	public BoardPaper selectContentByNO(int bid, int num)
			throws SQLException {
		HashMap map = makeTableMap(bid);
		map.put("num", num);
		return session.selectOne(makeSqlId("selectContentByNO"), map);
	}
	
	@Override
	public int updateContent(BoardPaper paper) {
		paper.setBoardId(makeTableName(paper.getBoardId()));
		return session.update(makeSqlId("updateContent"), paper);
	}

	@Override
	public int deleteContentByNO(int bid, int num) throws SQLException {
		HashMap map = makeTableMap(bid);
		map.put("num", num);
		return session.delete(makeSqlId("deleteContentByNO"), map);
	}
	
	@Override
	public int updateRestep(int bid, int refamily, int restep) {
		HashMap map = makeTableMap(bid);
		map.put("refamily", refamily);
		map.put("restep", restep);
		return session.update(makeSqlId("updateRestep"), map);
	}
	
	@Override
	public int insertContentForReply(BoardPaper paper) {
		paper.setBoardId(makeTableName(paper.getBoardId()));
		return session.insert(makeSqlId("insertContentForReply"), paper);
	}

	private String makeTableName(int boardId) {
		return "board_"+boardId+"_paper";
	}
	
	private String makeTableName(String boardId) {
		return "board_"+boardId+"_paper";
	}
	
	private HashMap makeTableMap(int bid) {
		HashMap map = new HashMap();
		map.put("tableName", makeTableName(bid));
		return map;
	}
	
	private String makeSqlId(String id){
		return "droowa.boardPaper."+id;
	}
}
